package com.deke.auth.filter;

import cn.hutool.json.JSONUtil;
import com.deke.entity.AclPermission;
import com.deke.utils.JwtTool;
import com.deke.vo.Result;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/12/2 9:59
 * @description：前置过滤器
 * @modified By：
 * @version:
 **/
@Component
public class JwtVerifyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest Request, HttpServletResponse Response, FilterChain filterChain) throws ServletException, IOException {
        //设置响应字符编码
        Response.setContentType("application/json;charset=utf-8");
        //通过请求拿到uri
        String path = Request.getRequestURI();
        //通过请求拿到请求方式
        String method = Request.getMethod();
        //如果是登录请求过滤
        if ("POST".equals(method) && "/login".equals(path)){
            filterChain.doFilter(Request,Response);
            return;
        }
        //通过请求头获取token
        String token = Request.getHeader("token");
        System.out.println(token);
        if (StringUtils.hasText(token)){
            //校验token是否通过
            boolean falg = JwtTool.verifyToken(token);
            if (falg){
                //把token中的内容拿出来
                Map<String, Object> tokenClaim = JwtTool.getTokenClaim(token);
                //拿到用户名
                String username = tokenClaim.get("username").toString();
                //拿到权限列表
                List<String> list = (List<String>) tokenClaim.get("authorities");
                //类型转换成SimpleGrantedAuthority
                List<SimpleGrantedAuthority> authorities = list.stream()
                        .map(item -> new SimpleGrantedAuthority(item))
                        .collect(Collectors.toList());
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(Request,Response);
                return;
            }
        }
        //当token无效时返回提示信息
        PrintWriter writer = Response.getWriter();
        Result result = new Result(500,"token值无效");
        //转换成json字符串
        String jsonStr = JSONUtil.toJsonStr(result);
        //输出对象输出
        writer.println(jsonStr);
        writer.flush();
        writer.close();
    }
}